package com.softwinner.awbt.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.design.widget.Snackbar;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.softwinner.awbt.R;
import com.softwinner.awbt.common.BTApplication;
import com.softwinner.awbt.common.MessageKey;
import com.softwinner.awbt.controller.BTController;
import com.softwinner.awbt.dao.Contact;
import com.softwinner.awbt.dao.ContactDao;
import com.softwinner.awbt.utils.LOG;

import java.util.List;


public class CallActivity extends Activity implements OnClickListener {
    private RelativeLayout rl_call_pager;
    private RelativeLayout rl_connect;
    private TextView tv_call_people_name;
    private Chronometer chronometer;
    private TextView tv_connection_info;
    private LinearLayout ll_number;
    private ImageView iv_number;
    private ImageView iv_guaduan;
    private ImageView iv_qieshengdao;
    private ImageView iv_bujingyin;

    // flag
    private boolean isShowNumber = false;
    // private boolean isPhoneConnection = false;
    // private boolean isInComing = false;
    private boolean volume_flag = false;
    private boolean isMute = false;
    private boolean isConnect = false;

    private String callNumber;// 前台拨号
    // private String calloutNumber;//后台拨号

    private static Handler hand = null;
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MessageKey.MSG_DISCONNECT:
                    finish();
                    break;
                case MessageKey.MSG_HANGUP_PHONE:
                case MessageKey.MSG_INCOMING_HANGUP:
                    LOG.d("handler------");
                    chronometer.stop();
                    finish();
                    break;
                case MessageKey.MSG_CALLOUT_CONNECT:
                    LOG.d("callNumber你是不是为空啊？" + callNumber);
                    if (callNumber != null) {
                        LOG.d("我都拨出去了，你接了没有哇");
                        callConnect(callNumber);
                    } else {
                        Handler handler2 = InComingActivity.getHandler();
                        if (handler2 != null) {
                            handler2.sendEmptyMessage(MessageKey.MSG_INCOMING_CONNECT);
                        }
                    }
                    break;
            }
        }

        ;
    };
    private String incomingNumber;
    private ImageView iv_one;
    private ImageView iv_two;
    private ImageView iv_three;
    private ImageView iv_four;
    private ImageView iv_five;
    private ImageView iv_six;
    private ImageView iv_seven;
    private ImageView iv_eight;
    private ImageView iv_nine;
    private ImageView iv_xinghao;
    private ImageView iv_zero;
    private ImageView iv_jinghao;

    public static Handler getHandler() {
        return hand;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LOG.d("CallActivity   onCreate");
        setContentView(R.layout.activity_call);
        initView();
        initData();
        isConnect();
        hand = handler;
    }

    private void isConnect() {
        if (isConnect) {
            rl_call_pager.setVisibility(View.GONE);
            rl_connect.setVisibility(View.VISIBLE);
//            if (callNumber != null) {
//                tv_connection_info.setText(callNumber);
//            }
//            if (incomingNumber != null) {
//                tv_connection_info.setText(incomingNumber);
//            }
            chronometer.setFormat("%s");
            chronometer.setBase(SystemClock.elapsedRealtime());// 复位键
            chronometer.start();

        } else {
            rl_call_pager.setVisibility(View.VISIBLE);
            rl_connect.setVisibility(View.GONE);
//            if (callNumber != null) {
//                tv_call_people_name.setText(callNumber);
//            }
            /*
             * if(calloutNumber!=null){
             * tv_call_people_name.setText(calloutNumber); callNumber = null; }
             */
        }
    }

    protected void callOut(String phoneNumber) {
        placeCall(phoneNumber);
        rl_call_pager.setVisibility(View.VISIBLE);
        rl_connect.setVisibility(View.GONE);
        tv_call_people_name.setText(phoneNumber);
    }

    protected void callConnect(String callNumber2) {
        rl_call_pager.setVisibility(View.GONE);
        rl_connect.setVisibility(View.VISIBLE);

        tv_connection_info.setText(callNumber2);

        chronometer.setFormat("%s");
        chronometer.setBase(SystemClock.elapsedRealtime());// 复位键
        chronometer.start();
    }

    private void initData() {
        Intent intent = getIntent();
        callNumber = intent.getStringExtra("callNumber");
        LOG.i("CallActivity中拨出电话号" + callNumber);
        incomingNumber = intent.getStringExtra("incomingNumber");
        // calloutNumber = intent.getStringExtra("calloutNumber");
        isConnect = intent.getBooleanExtra("isConnect", false);
        if (!TextUtils.isEmpty(callNumber)) {
            List<Contact> contacts = BTApplication.getInstance().getDaoSession().getContactDao()
                    .queryBuilder().where(ContactDao.Properties.Number.eq(callNumber)).list();
            if (contacts.size() == 0) {
                tv_call_people_name.setText(callNumber);
                LOG.i("没有名字的号码");
            } else {
                tv_call_people_name.setText(contacts.get(0).getName());
            }
        }

        if (!TextUtils.isEmpty(incomingNumber)) {
            List<Contact> contacts = BTApplication.getInstance().getDaoSession().getContactDao()
                    .queryBuilder().where(ContactDao.Properties.Number.eq(incomingNumber)).list();
            if (contacts.size() == 0) {
                tv_call_people_name.setText(incomingNumber);
                LOG.i("没有名字的号码");
            } else {
                tv_call_people_name.setText(contacts.get(0).getName());
            }
        }
    }

    private void initView() {
        rl_call_pager = (RelativeLayout) findViewById(R.id.rl_call_pager);
        tv_call_people_name = (TextView) findViewById(R.id.tv_call_people_name);

        rl_connect = (RelativeLayout) findViewById(R.id.rl_connect);
        chronometer = (Chronometer) findViewById(R.id.chronometer);
        tv_connection_info = (TextView) findViewById(R.id.tv_connection_info);

        ll_number = (LinearLayout) findViewById(R.id.ll_number);

        iv_number = (ImageView) findViewById(R.id.iv_number);
        iv_guaduan = (ImageView) findViewById(R.id.iv_guaduan);
        iv_qieshengdao = (ImageView) findViewById(R.id.iv_qieshengdao);
        iv_bujingyin = (ImageView) findViewById(R.id.iv_bujingyin);

        iv_one = (ImageView) findViewById(R.id.iv_one);
        iv_two = (ImageView) findViewById(R.id.iv_two);
        iv_three = (ImageView) findViewById(R.id.iv_three);
        iv_four = (ImageView) findViewById(R.id.iv_four);
        iv_five = (ImageView) findViewById(R.id.iv_five);
        iv_six = (ImageView) findViewById(R.id.iv_six);
        iv_seven = (ImageView) findViewById(R.id.iv_seven);
        iv_eight = (ImageView) findViewById(R.id.iv_eight);
        iv_nine = (ImageView) findViewById(R.id.iv_nine);
        iv_xinghao = (ImageView) findViewById(R.id.iv_xinghao);
        iv_zero = (ImageView) findViewById(R.id.iv_zero);
        iv_jinghao = (ImageView) findViewById(R.id.iv_jinghao);

        iv_one.setOnClickListener(this);
        iv_two.setOnClickListener(this);
        iv_three.setOnClickListener(this);
        iv_four.setOnClickListener(this);
        iv_five.setOnClickListener(this);
        iv_six.setOnClickListener(this);
        iv_seven.setOnClickListener(this);
        iv_eight.setOnClickListener(this);
        iv_nine.setOnClickListener(this);
        iv_xinghao.setOnClickListener(this);
        iv_zero.setOnClickListener(this);
        iv_jinghao.setOnClickListener(this);

        iv_number.setOnClickListener(this);
        iv_guaduan.setOnClickListener(this);
        iv_qieshengdao.setOnClickListener(this);
        iv_bujingyin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_number:
                showNumber();
                break;
            case R.id.iv_guaduan:
                hangUp();
                break;
            case R.id.iv_qieshengdao:
                if (BTApplication.getInstance().getStatus() > 0) {
                    switchCarAndphone();
                } else {
                    Toast.makeText(this, "请您先连接设备", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_bujingyin:
                switchMute();
                break;
            case R.id.iv_one:
                phoneDTMFCode('1');
                break;
            case R.id.iv_two:
                phoneDTMFCode('2');
                break;
            case R.id.iv_three:
                phoneDTMFCode('3');
                break;
            case R.id.iv_four:
                phoneDTMFCode('4');
                break;
            case R.id.iv_five:
                phoneDTMFCode('5');
                break;
            case R.id.iv_six:
                phoneDTMFCode('6');
                break;
            case R.id.iv_seven:
                phoneDTMFCode('7');
                break;
            case R.id.iv_eight:
                phoneDTMFCode('8');
                break;
            case R.id.iv_nine:
                phoneDTMFCode('9');
                break;
            case R.id.iv_xinghao:
                phoneDTMFCode('*');
                break;
            case R.id.iv_zero:
                phoneDTMFCode('0');
                break;
            case R.id.iv_jinghao:
                phoneDTMFCode('#');
                break;
        }
    }

    private void phoneDTMFCode(char code) {
        try {
            BTController.getInstance().phoneTransmitDTMFCode(code);
        } catch (RemoteException e) {
            showMessage(R.string.remote_exception_alert);
        }
    }

    private void switchMute() {
        isMute = !isMute;
        if (isMute) {
            iv_bujingyin.setImageResource(R.drawable.ic_mute_off);
        } else {
            iv_bujingyin.setImageResource(R.drawable.ic_mute_on);
        }

        try {
            BTController.getInstance().setMicMute(isMute);
        } catch (RemoteException e) {
            showMessage(R.string.remote_exception_alert);
        }
    }

    // 切换声音在车机端与手机端
    private void switchCarAndphone() {
        volume_flag = !volume_flag;
        if (volume_flag) {// 手机端
            try {
                BTController.getInstance().phoneTransfer();
            } catch (RemoteException e1) {
                showMessage(R.string.remote_exception_alert);
            }
            showMessage(R.string.phone_device);
        } else {// 车机端
            try {
                BTController.getInstance().phoneTransferBack();
            } catch (RemoteException e1) {
                showMessage(R.string.remote_exception_alert);
            }
            showMessage(R.string.car_device);
        }
    }

    private void showNumber() {
        isShowNumber = !isShowNumber;
        if (isShowNumber) {
            ll_number.setVisibility(View.VISIBLE);
        } else {
            ll_number.setVisibility(View.INVISIBLE);
        }
    }

    // 挂断
    private void hangUp() {

        // Toast.makeText(this, "挂断", 0).show();
        try {
            BTController.getInstance().phoneHangUp();
        } catch (RemoteException e) {
            showMessage(R.string.remote_exception_alert);
        }

    }

    // 拨打正确的电话
    private void placeCall(String mLastNumber) {
        if (mLastNumber.length() == 0) return;
        if (PhoneNumberUtils.isGlobalPhoneNumber(mLastNumber)) {
            if (mLastNumber == null || !TextUtils.isGraphic(mLastNumber)) {
                return;
            }
            try {
                BTController.getInstance().callPhone(mLastNumber);
            } catch (RemoteException e) {
                showMessage(R.string.remote_exception_alert);
            }
        }
    }

    @Override
    protected void onResume() {
        LOG.i("CallActivity-----onResume---");
        super.onResume();
    }


    public void showMessage(int message) {
        if (iv_one != null) {
            Snackbar.make(iv_one, message, Snackbar.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }

    }
}
